package session

import (
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"myadmin/sys/cache/mapstore"
	"myadmin/sys/tool"
	"time"
)

//数据库session
type SysSession struct {
	Id         string    `orm:"pk;type(char);size(50);unique" json:"id"`
	Data       string    `orm:"type(text)" json:"data"`
	CreateTime int64       `orm:"" json:"createtime"` //创建时间戳
}


func InitSysSession() *SysSession{
	return &SysSession{
		Id:tool.GetUUID(),
		CreateTime:time.Now().Unix(),
	}
}
func NewSysSession () *SysSession{
	return &SysSession{}
}


//保存session
func (this *SysSession) Add(session *Session) string{
	o := orm.NewOrm()
	v, _ := json.Marshal(session)
	s:=InitSysSession()
	s.Data = string(v)
	//fmt.Println("will ", s)
	o.Insert(s)
	//fmt.Println(num,err)
	return s.Id
}

func (this *SysSession) Get(k string) *Session {
	o := orm.NewOrm()
	this.Id = k
	err:=o.Read(this, "Id")
	if err== orm.ErrNoRows{
		return nil
	}
	if this.CreateTime+int64(mapstore.Get("exp").(int)) <
		time.Now().Unix(){
		o.Delete(this)
		return nil
	}
	rawData := []byte(this.Data)
	var session Session
	json.Unmarshal(rawData, &session)
	return &session
}


func (this *SysSession) Update(k string,v *Session) {
	//千万不要在 this上更新 全局用一个this
	o := orm.NewOrm()
	d, _ := json.Marshal(v)
	sel:=NewSysSession()
	sel.Id = k
	sel.Data = string(d)
	o.Update(sel,"Data")
}

func(this *SysSession) UpdateTime(k string,v *Session){
	o:=orm.NewOrm()
	sel:=NewSysSession()
	v.ActiveTime = time.Now().Unix()
	d,_:=json.Marshal(v)
	sel.Id = k
	sel.Data = string(d)
	o.Update(sel,"Data")
	//fmt.Println(n,err)
}


func (this *SysSession) Del(k string) {
	o:=orm.NewOrm()
	sel:=NewSysSession()
	sel.Id = k
	o.Delete(sel)
}
